package com.permission.service.impl;

import com.permission.dao.RoleDao;
import com.permission.model.Role;
import com.permission.service.RoleService;
import com.permission.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class RoleServiceImpl implements RoleService {

    @Override
    public Role getRoleWithMenusById(Long id) {
        try (SqlSession session = MyBatisUtil.getSession()) {
            RoleDao roleDao = session.getMapper(RoleDao.class);
            return roleDao.selectRoleWithMenusById(id);
        }
    }

    @Override
    public Role getRoleWithMenusByKey(String roleKey) {
        try (SqlSession session = MyBatisUtil.getSession()) {
            RoleDao roleDao = session.getMapper(RoleDao.class);
            return roleDao.selectRoleWithMenusByKey(roleKey);
        }
    }

    @Override
    public List<Role> getAllRoles() {
        try (SqlSession session = MyBatisUtil.getSession()) {
            RoleDao roleDao = session.getMapper(RoleDao.class);
            return roleDao.selectAllRoles();
        }
    }

    @Override
    public void updateRoleMenus(Long roleId, List<Long> menuIds) {
        SqlSession session = MyBatisUtil.getSession();
        try {
            RoleDao roleDao = session.getMapper(RoleDao.class);
            // 先删除原有权限关系
            roleDao.deleteRoleMenus(roleId);
            // 新增权限关系
            if (menuIds != null && !menuIds.isEmpty()) {
                for (Long menuId : menuIds) {
                    roleDao.insertRoleMenu(roleId, menuId);
                }
            }
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException("更新角色权限失败", e);
        } finally {
            session.close();
        }
    }
}